package icu.luoxi.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @author Cao Jiwen
 * @version V1.0
 */
public class EmailUtils {

    /**
     * @param username 发送方邮箱地址
     * @param password 邮箱授权码
     * @param toEmail 收件人地址
     * @param subject 邮件主题
     * @param content 邮件正文内容
     * @throws MessagingException 消息异常
     * @throws UnsupportedEncodingException 发送异常
     */
    public static void sendEmail(String username, String password, String toEmail, String subject, String content) throws MessagingException, UnsupportedEncodingException {
        String host = getHost(username);
        // 配置邮件客户端属性
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", 465);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");

        // 创建会话
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // 创建邮件消息
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username,"洛希极限"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(subject);
        message.setText(content);

        // 发送邮件
        Transport.send(message);
    }

    private static String getHost(String Email){
        String host = null;
        if (Email.contains("@qq.com")){
            host = "smtp.qq.com";
        }else if (Email.contains("@163.com")){
            host = "smtp.163.com";
        }else if (Email.contains("@126.com")){
            host = "smtp.126.com";
        }
        return host;
    }
}
